<template>
  <div class="departments-container">
    <div v-loading="isLoading" class="app-container">
      <el-card class="tree-card">
        <!-- 用了一个行列布局 -->
        <TreeTools :tree-node="company" :is-root="true" @addDepts="addDepts" />
        <el-tree :data="departs" :props="defaultProps" default-expand-all>
          <TreeTools slot-scope="{data}" :tree-node="data" @editDepts="editDepts" @addDepts="addDepts" @updateDeparts="getDepartments" />
        </el-tree>
      </el-card>
    </div>
    <AddDept
      ref="addDept"
      v-model="showDialog"
      :tree-node="node"
      :show-dialog.sync="showDialog"
      @addDepts="getDepartments"
    />
  </div>
</template>

<script>
import TreeTools from './components/tree-tools.vue'
import { getDepartmentsApi } from '@/api/departments'
import { tranListToTreeData } from '@/utils'
import AddDept from './components/add-dept'
export default {
  components: {
    TreeTools,
    AddDept
  },
  data() {
    return {
      defaultProps: {
        label: 'name' // label默认的值是：'label'
        // children:'children' //这个可以省略，children默认的就是'children'
      },
      departs: [],
      company: {},
      showDialog: false, // 控制添加部门弹窗的显示
      node: null,
      isLoading: false // 加载状态
    }
  },
  created() {
    this.getDepartments()
  },
  methods: {
    async getDepartments() {
      this.isLoading = true
      try {
        const result = await getDepartmentsApi()
        this.company = { name: '精武门', manager: '负责人', id: '' }
        // this.departs = result.depts
        this.departs = tranListToTreeData(result.depts, '')
      } catch (err) {
        this.$message.error('获取失败')
      }
      this.isLoading = false
    },
    addDepts(treeNode) {
      this.showDialog = true // 显示弹层
      // 因为treeNode 是当前的点击部门，此时这个部门应该记录下来
      this.node = treeNode
    },
    editDepts(treeNode) {
      this.showDialog = true// 显示弹层
      this.node = treeNode // 赋值操作的节点
      // 我们需要在这个位置 调用子组件的方法
      // 父组件 调用子组件的方法
      this.$refs.addDept.getDepartDetail(treeNode.id) // 直接调用子组件中的方法 传入一个id
    }
  }
}
</script>

<style scoped>
.tree-card {
  padding: 30px  140px;
  font-size:14px;
}
</style>
